<?php

namespace app\api\controller;

use app\admin\library\Auth;
use app\common\controller\Api;
use think\Db;
use think\exception\PDOException;

/**
 * 手机短信接口
 */
class Vultr extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $api_key = null;
    protected $Myvultros = null;
    protected $Myvultrregions = null;
    protected $Myvultrplans = null;
    protected $Myvultrinstances = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->api_key = 'GC4OGFF4MAHLT44OA3C4EDHJAJL2R5U3Z7XQ';
        $this->Myvultros = new \app\admin\model\Myvultros;
        $this->Myvultrregions = new \app\admin\model\Myvultrregions;
        $this->Myvultrplans = new \app\admin\model\Myvultrplans;
        $this->Myvultrinstances = new \app\admin\model\Myvultrinstances;
    }

    /**
     * 获取账户信息
     */
    public function account()
    {
        $url = "https://api.vultr.com/v2/account";
        $data = $this->geturl($url);
        if($data){
            $return = json_decode($data,true);
            $this->success('获取数据',$return);
        }else{
            $this->success('接口无返回数据');
        }
    }
    /**
     * 列出操作系统
     */
    public function os()
    {
        $url = "https://api.vultr.com/v2/os";
        $data = $this->geturl($url);
        if($data){
            $json_data = json_decode($data,true);
            $os = $json_data['os'];
            if (!empty($os)) {
                foreach ($os as $o) {
                    $row['os_id'] = $o['id'];
                    $row['name'] = $o['name'];
                    $row['arch'] = $o['arch'];
                    $row['family'] = $o['family'];
                    if (!empty($row)) {
                        $insert[] = $row;
                    }
                }
                $return = $this->Myvultros->saveAll($insert);
                $this->success('获取数据',$return);
            }
            $this->success('获取数据',$json_data);
        }else{
            $this->success('接口无返回数据');
        }
    }
    /**
     * 列出地区
     */
    public function regions()
    {
        $url = "https://api.vultr.com/v2/regions";
        $data = $this->geturl($url);
        if($data){
            $json_data = json_decode($data,true);
            $regions = $json_data['regions'];

            if (!empty($regions)) {
                foreach ($regions as $v) {
                    $row['regions_id'] = $v['id'];
                    $row['city'] = $v['city'];
                    $row['country'] = $v['country'];
                    $row['continent'] = $v['continent'];
                    $row['options'] = json_encode($v['options']);
                    if (!empty($row)) {
                        $insert[] = $row;
                    }
                }
                $return = $this->Myvultrregions->saveAll($insert);
                $this->success('获取数据',$return);
            }
            $this->success('获取数据',$json_data);
        }else{
            $this->success('接口无返回数据');
        }
    }
    /**
     * 列出实例
     */
    public function instances()
    {
        $url = "https://api.vultr.com/v2/instances";
        $data = $this->geturl($url);
        if($data){
            $json_data = json_decode($data,true);
            $instances = $json_data['instances'];
            if (!empty($instances)) {
                foreach ($instances as $v) {
                    $row['instances_id'] = $v['id'];
                    $row['os_id'] = $v['os_id'];
                    $row['plan'] = $v['plan'];
                    $row['region'] = $v['region'];
                    $row['power_status'] = $v['power_status'];
                    $row['server_status'] = $v['server_status'];
                    if (!empty($row)) {
                        $insert[] = $row;
                    }
                }
                $return = $this->Myvultrinstances->saveAll($insert);
                $this->success('获取数据',$return);
            }
            $this->success('获取数据',$json_data);
        }else{
            $this->success('接口无返回数据');
        }
    }
    /**
     * 列出计划
     */
    public function plans()
    {
        $url = "https://api.vultr.com/v2/plans";
        $data = $this->geturl($url);
        if($data){
            $json_data = json_decode($data,true);
            $plans = $json_data['plans'];
            if (!empty($plans)) {
                foreach ($plans as $v) {
                    $row['plans_id'] = $v['id'];
                    $row['vcpu_count'] = $v['vcpu_count'];
                    $row['ram'] = $v['ram'];
                    $row['disk'] = $v['disk'];
                    $row['disk_count'] = $v['disk_count'];
                    $row['bandwidth'] = $v['bandwidth'];
                    $row['monthly_cost'] = $v['monthly_cost'];
                    $row['type'] = $v['type'];
                    if (!empty($v['locations'])) {
                        foreach ($v['locations'] as $location) {
                            $regionsplans = Db::name('myvultr_regionsplans')->where('regions_id',$location)->where('plans_id',$row['plans_id'])->find();
                            if (empty($regionsplans)) {
                                Db::name('myvultr_regionsplans')->where('regions_id',$location)->where('plans_id',$row['plans_id'])->insert(
                                    [
                                        'createtime' => time(),
                                        'regions_id' => $location,
                                        'plans_id' => $row['plans_id'],
                                    ]
                                );
                            }
                        }
                    }
                    if (!empty($row)) {
                        $insert[] = $row;
                    }
                }
                $return = $this->Myvultrplans->saveAll($insert);
                $this->success('获取数据',$return);
            }
            $this->success('获取数据',$json_data);
        }else{
            $this->success('接口无返回数据');
        }
    }
    /**
     * 创建实例
     */
    public function postinstances($post = null)
    {
        $this->api_key = $this->select_account();
        if (empty($this->api_key)) {
            $error['status'] = 401;
            return $error;
        } else {
            $this->error('暂无账户');
        }

        $os = Db::name('myvultr_os')->where('id',$post['os_id'])->find();
        $region = Db::name('myvultr_regions')->where('id',$post['region'])->find();
        $plans = Db::name('myvultr_regionsplans')->where('id',$post['plan'])->find();
        if (empty($os) || empty($region) || empty($plans)) {
            $this->error('传参错误');
        }
        $url = "https://api.vultr.com/v2/instances";
        $arr = array();
        $arr['region'] = $region['regions_id'];
        $arr['plan'] = $plans['plans_id'];
        $arr['label'] = '';
        $arr['os_id'] = $os['os_id'];
        $arr['user_data'] = '';
        $arr['backups'] = 'enabled';//启用备份
        $data = $this->posturl($url,$arr);

        if($data){
            $json_data = json_decode($data,true);
            if (!empty($json_data['error'])) {
                if (!empty($post)) {
                    return $json_data;
                } else {
                    $this->error('接口错误',$json_data['error']);
                }
            }
            if (!empty($json_data['instances'])) {
                $instances = $json_data['instances'];
                //保存快照
                dump($instances);
                die;
                $this->snapshots($instances);
                foreach ($instances as $v) {
                    $row['instances_id'] = $v['id'];
                    $row['os_id'] = $v['os_id'];
                    $row['plan'] = $v['plan'];
                    $row['region'] = $v['region'];
                    $row['power_status'] = $v['power_status'];
                    $row['server_status'] = $v['server_status'];
                    $row['email'] = $post['email'];
                    if (!empty($row)) {
                        $insert[] = $row;
                    }
                }
                $return = $this->Myvultrinstances->saveAll($insert);
                $this->success('获取数据',$return);
            }
            $this->success('获取数据',$json_data);
        }else{
            $this->success('接口无返回数据');
        }
    }

    /**
     * 创建快照
     */
    public function snapshots($instance = null)
    {
        $url = "https://api.vultr.com/v2/snapshots";
        $arr = array();
//        $arr['instance_id'] = $instance['instance_id'];
        $arr['instance_id'] = 'cdaa6e90-18d2-436b-913b-2f06d51b4545';
        $arr['description'] = 'test2';
        $data = $this->posturl($url,$arr);
        if($data){
            $json_data = json_decode($data,true);
            if (!empty($json_data['error'])) {
                if (!empty($instance)) {
                    return $json_data;
                } else {
                    $this->error('接口错误',$json_data['error']);
                }
            }
            if (!empty($json_data['snapshot'])) {
                $snapshot = $json_data['snapshot'];
                $row['instance_id'] = $arr['instance_id'];
                $row['snapshot_id'] = $snapshot['id'];
                $row['date_created'] = $snapshot['date_created'];
                $row['description'] = $snapshot['description'];
                $row['size'] = $snapshot['size'];
                $row['status'] = $snapshot['status'];
                $row['os_id'] = $snapshot['os_id'];
                $row['app_id'] = $snapshot['app_id'];
                $row['createtime'] = time();
                $row['updatetime'] = time();
                $row['email'] = '';
                Db::name('myvultr_snapshot')->insert($row);
                $this->success('获取数据', $json_data);
            }
        }else{
            $this->success('接口无返回数据');
        }
    }

    /**
     * 创建实例
     */
    public function supplement_plans($post = null)
    {
        $plans = Db::name('myvultr_plans')->select();
        foreach ($plans as $plan) {
            Db::name('myvultr_regionsplans')->where('plans_id',$plan['plans_id'])->update(
                [
                    'disk'=>$plan['disk'],
                    'monthly_cost'=>$plan['monthly_cost']
                ]
            );
        }
        $this->success('操作成功');
    }

    function geturl($url){
        $headerArray = array("Content-Type:application/json;",'Authorization:Bearer '.$this->api_key);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function posturl($url,$data = array()){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $headerArray = array("Content-Type:application/json;",'Authorization:Bearer '.$this->api_key);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}
